﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Reflection;
using ZLCMS.Data.Model;
using DotNet.Common.Command;
using ZLCMS.Business.Util;

namespace ZLCMS.Web.ZLOAuth.Code
{
    public class ExternalInterfaceParameter : CommandParameter
    {
        public string timestamp { get { return _timestamp; } set { _timestamp = value; } }

        private string _timestamp = string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now);
    }


    /// <summary>
    /// 外部接口
    /// </summary>
    public abstract class ExternalInterfaceCommand<T> : Command<T> where T : new()
    {
        protected abstract string Key { get; }


        protected override ICommandResult<T> OnExecute(ICommandParameter parameter)
        {
            ICommandResult<T> result = new CommandResult<T>();

            WebRequest request = null;

            string data = "key=" + Key + "&param=" + JsonConvert.SerializeObject(parameter) + "&private=" + ParamKit.GetValue("ZlcmsOAuth", "AppSecret", "");
            string sign =
                 System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(data, "MD5").ToLower();

            request = WebRequest.Create(ParamKit.GetValue("ZlcmsOAuth", "InterfaceUrl", "") + "?key=" + Key + "&param=" + System.Web.HttpUtility.UrlEncode(JsonConvert.SerializeObject(parameter)) + "&user=" + ParamKit.GetValue("ZlcmsOAuth", "AppId", "")
                + "&sign=" + sign);
                request.Method = "GET";

                request.Headers.Set("Cache-Control", " no-cache");

           
            WebResponse response = null;
            bool callError = false;
            try
            {
                response = request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response;
                callError = true;
            }

            System.IO.Stream respStream = response.GetResponseStream();
            string responseString = "";
            using (System.IO.StreamReader reader = new System.IO.StreamReader(respStream, UTF8Encoding.UTF8))
            {
                responseString = reader.ReadToEnd();
            }
            if (callError)
            {
                result.ErrorCode = "0001";
                result.ErrorMsg = "调用接口出错";
            }
            else
            {
                result = JsonConvert.DeserializeObject<CommandResult<T>>(responseString);
            }
            return result;
        }
    }
}
